package com.math.aistudykbr.controller;

import com.math.aistudykbr.exception.UnauthorizedException;
import com.math.aistudykbr.exception.UserException;
import com.math.aistudykbr.pojo.entity.User;
import com.math.aistudykbr.pojo.dto.UserDTO;
import com.math.aistudykbr.pojo.vo.UserVO;
import com.math.aistudykbr.service.UserService;
import com.math.aistudykbr.utils.JwtUtil;
import com.math.aistudykbr.utils.Result;
import com.math.aistudykbr.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/user")
public class UserController {

    private final UserService userService;

    private final JwtUtil jwtUtil;

    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) throws UserException {

        userService.saveUser(user);

        return Result.success(200, "注册成功", null);
    }

    @PostMapping("/login")
    public Result<UserVO> login(@RequestBody UserDTO userDTO) throws UserException {
        log.error("用户登录:{}", userDTO);
        return Result.success(200, "登录成功", userService.selectUserByUsernameAndPassword(userDTO));
    }

    @PostMapping("/refreshToken")
    public Result<String> refreshToken(@RequestHeader("token") String token) throws UnauthorizedException {
        log.info("用户刷新Token：{}", token);
        return Result.success(200, "刷新Token成功", jwtUtil.refreshToken(token));
    }
}
 